<template>
  <div class="publish-property-page">
    <el-container>
      <el-header class="page-header">
        <el-button @click="$router.back()" icon="ArrowLeft" text>返回</el-button>
        <h2>发布房源</h2>
      </el-header>

      <el-main>
        <el-card class="form-card" shadow="never">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="property-form"
          >
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="房源标题" prop="title">
                  <el-input
                    v-model="form.title"
                    placeholder="请输入房源标题"
                    maxlength="50"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="房源类型" prop="room_type">
                  <el-select v-model="form.room_type" placeholder="选择房源类型" style="width: 100%">
                    <el-option label="公寓" value="apartment" />
                    <el-option label="别墅" value="villa" />
                    <el-option label="写字楼" value="office" />
                    <el-option label="商铺" value="shop" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="价格" prop="price">
                  <el-input-number
                    v-model="form.price"
                    :min="0"
                    :step="100"
                    placeholder="月租金"
                    style="width: 100%"
                  />
                  <span class="unit">元/月</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="面积" prop="area">
                  <el-input-number
                    v-model="form.area"
                    :min="0"
                    :step="1"
                    placeholder="建筑面积"
                    style="width: 100%"
                  />
                  <span class="unit">㎡</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="房源状态" prop="status">
                  <el-select v-model="form.status" placeholder="选择状态" style="width: 100%">
                    <el-option label="可租" value="available" />
                    <el-option label="已租" value="rented" />
                    <el-option label="已售" value="sold" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="卧室" prop="bedrooms">
                  <el-input-number
                    v-model="form.bedrooms"
                    :min="0"
                    :max="10"
                    placeholder="卧室数量"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客厅" prop="living_rooms">
                  <el-input-number
                    v-model="form.living_rooms"
                    :min="0"
                    :max="10"
                    placeholder="客厅数量"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="卫生间" prop="bathrooms">
                  <el-input-number
                    v-model="form.bathrooms"
                    :min="0"
                    :max="10"
                    placeholder="卫生间数量"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="城市" prop="city">
                  <el-select v-model="form.city" placeholder="选择城市" style="width: 100%">
                    <el-option v-for="city in cities" :key="city" :label="city" :value="city" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="区域" prop="district">
                  <el-input
                    v-model="form.district"
                    placeholder="请输入区域"
                    maxlength="20"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入详细地址"
                maxlength="100"
              />
            </el-form-item>

            <el-form-item label="房源描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请详细描述房源信息，如装修情况、周边配套、交通便利性等..."
                :rows="4"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="房源图片">
              <el-upload
                v-model:file-list="form.images"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :limit="9"
                accept="image/*"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">
                <p>支持 JPG、PNG 格式，最多上传9张图片</p>
                <p>建议尺寸：800x600像素，文件大小不超过2MB</p>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="large" @click="submitForm" :loading="submitting">
                <el-icon><Check /></el-icon>
                发布房源
              </el-button>
              <el-button size="large" @click="resetForm">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button size="large" @click="$router.back()">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="800px">
      <img :src="previewUrl" style="width: 100%; height: auto;" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { propertiesAPI } from '@/api/properties'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const formRef = ref()
const submitting = ref(false)
const previewVisible = ref(false)
const previewUrl = ref('')

const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '南京', '武汉', '西安', '重庆']

const form = reactive({
  title: '',
  description: '',
  price: null,
  area: null,
  address: '',
  city: '',
  district: '',
  room_type: 'apartment',
  bedrooms: 1,
  living_rooms: 1,
  bathrooms: 1,
  status: 'available',
  images: []
})

const rules = {
  title: [
    { required: true, message: '请输入房源标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度在 5 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 1, message: '价格必须大于0', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' },
    { type: 'number', min: 1, message: '面积必须大于0', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  district: [
    { required: true, message: '请输入区域', trigger: 'blur' }
  ]
}

const handlePreview = (file) => {
  previewUrl.value = file.url || file.thumbUrl
  previewVisible.value = true
}

const handleRemove = (file, fileList) => {
  form.images = fileList
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 处理图片数据
    const imageUrls = form.images.map(img => {
      if (img.url) return img.url
      if (img.response?.url) return img.response.url
      return null
    }).filter(Boolean)

    const submitData = {
      ...form,
      images: imageUrls
    }

    const res = await propertiesAPI.create(submitData)
    
    if (res?.success) {
      ElMessage.success('房源发布成功！')
      ElMessageBox.confirm(
        '房源发布成功，是否查看房源详情？',
        '提示',
        {
          confirmButtonText: '查看详情',
          cancelButtonText: '继续发布',
          type: 'success',
        }
      ).then(() => {
        router.push(`/properties/${res.data.id}`)
      }).catch(() => {
        resetForm()
      })
    } else {
      ElMessage.error(res?.message || '发布失败')
    }
  } catch (error) {
    console.error('发布房源失败:', error)
    ElMessage.error('发布失败，请重试')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.images = []
}
</script>

<style scoped>
.publish-property-page {
  min-height: 100vh;
  background: #f6f8fb;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  height: 72px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.form-card {
  max-width: 1000px;
  margin: 0 auto;
  border-radius: 8px;
}

.property-form {
  padding: 24px;
}

.unit {
  margin-left: 8px;
  color: #8c8c8c;
  font-size: 14px;
}

.upload-tip {
  margin-top: 8px;
  color: #8c8c8c;
  font-size: 12px;
}

.upload-tip p {
  margin: 4px 0;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>
